/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package com.home.gui;

import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.ListMultimap;
import com.home.common.ApplicationCommon;
import com.home.common.Constants;
import com.home.common.IndexedFocusTraversalPolicy;
import com.home.common.SchemeType;
import com.home.common.utils.DateUtils;
import com.home.components.ModalJInternalFrame;
import com.home.item.AgentComboItem;
import com.home.item.SchemeComboItem;
import com.home.item.SubjectComboItem;
import com.home.logic.AgentLogic;
import com.home.logic.AttributeGroupLogic;
import com.home.logic.SchemeLogic;
import com.home.logic.ScorecardDetailsLogic;
import com.home.logic.ScorecardDetailsResultLogic;
import com.home.logic.ScorecardGroupAttributeResultLogic;
import com.home.logic.ScorecardLogic;
import com.home.logic.SubjectLogic;
import com.home.mapping.Agent;
import com.home.mapping.Attribute;
import com.home.mapping.AttributeGroup;
import com.home.mapping.Scheme;
import com.home.mapping.Scorecard;
import com.home.mapping.ScorecardDetails;
import com.home.mapping.ScorecardDetailsResult;
import com.home.mapping.ScorecardGroupAttributeResult;
import com.home.mapping.ScorecardType;
import com.home.mapping.Subject;
import com.home.mapping.Team;
import com.home.mapping.Venture;
import com.home.model.table.EditableCellFocusAction;
import com.home.model.table.ScorecardDetailObjTable;
import com.home.table.editor.AlignmentCenterTableScorecardHeaderCellRenderer;
import com.home.table.editor.ColorColumnRenderer;
import com.home.table.editor.JTableX;
import com.home.table.editor.RowEditorModel;
import com.home.table.editor.ScorecardDetailsTableModel;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Insets;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.concurrent.ExecutionException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.DefaultCellEditor;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSeparator;
import javax.swing.JTextArea;
import javax.swing.KeyStroke;
import javax.swing.SwingConstants;
import javax.swing.SwingWorker;
import javax.swing.border.EmptyBorder;
import javax.swing.event.InternalFrameAdapter;
import javax.swing.event.InternalFrameEvent;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableColumn;
/**
 *
 * @author vi
 */
public class AgentScorecard extends ModalJInternalFrame {
    private ScorecardType type;
    private boolean isUpdate;
    private Agent agent;
    private Agent agentLogin;
    private Scorecard currentScorecard;
    //private Map<Integer,Scheme> mapScheme = new HashMap<Integer,Scheme>();
    private List<Scheme> listScheme = new ArrayList<>();
    private List<ScorecardDetails> listScorecardDetails = new ArrayList<>();
    //private Map<Integer,Scheme> mapSchemeResult = new HashMap<Integer,Scheme>();
    private Map<Integer,Agent> mapAgent = new HashMap<>();
    private List<AttributeGroup> groups = new ArrayList<>();
    private List<ScorecardDetailObjTable> listScObjectTable = new ArrayList<>();
    private MainScreen main;
    private Subject selectedSubject = new Subject();
    private QAWorkingList qaWorkList;
    /**
     * Creates new form AgentScorecard
     */
    public AgentScorecard(MainScreen main, ScorecardType type, Agent agent, Venture venture, final Scorecard scorecard, Map<Integer, Agent> mapAgent, QAWorkingList qaWorkList) {
        initComponents();
        
        this.setModal(true);
        
        this.setTitle(type.getType() + " Scorecard");
        
        setBounds(ApplicationCommon.getRectangleForCenter(main.getSize().width, main.getSize().height - 90, this.getWidth(), this.getHeight()));
        
        this.main = main;
        this.type = type;
        this.agent = agent;
        this.currentScorecard = scorecard;
        this.agentLogin = main.getAgentLogin();
        this.qaWorkList = qaWorkList;
        
        // control tabindex
        IndexedFocusTraversalPolicy policy = new IndexedFocusTraversalPolicy();
        policy.addIndexedComponent(chooserTransDate);
        policy.addIndexedComponent(chooserEvaluationDate);
        policy.addIndexedComponent(cboTeamLeader);
        //policy.addIndexedComponent(cboEvaluator);
        policy.addIndexedComponent(txtOrderNo);        
        policy.addIndexedComponent(txtPhone);
        policy.addIndexedComponent(txtDuration);  
        policy.addIndexedComponent(txtZendeskTicketNumber);
        if(type.getIdScorecardType().compareTo(Constants.SCORECARD_TYPE_DIGITAL_ID) != 0) {
            policy.addIndexedComponent(txtRecordingId);
        }
        setFocusTraversalPolicy(policy);
       
        
        if (scorecard.getIdScorecard() != null) {
            isUpdate = true;
        } else {
            isUpdate = false;
        }
        this.mapAgent = mapAgent;
                       
        txtSubject.setEditable(false);
        // fill data for combo : team lead & evaluator
        cboTeamLeader.removeAllItems();
//        cboEvaluator.removeAllItems();
        List<Agent> listTeamLead = new AgentLogic().findTeamLeadByVenture(venture.getIdVenture());
//        List<Agent> listAgentQA = new AgentLogic().findQAByVenture(venture.getIdVenture());
        
        
        for (Agent ag : listTeamLead) {
            cboTeamLeader.addItem(new AgentComboItem(ag));            
        }
                        
//        for (Agent evaluator : listAgentQA) {
//            cboEvaluator.addItem(new AgentComboItem(evaluator));
//        }               
//        int indexTemlead = getIndexAgent(main.getAgentLogin().getIdAgent(), cboEvaluator);
//        cboEvaluator.setSelectedIndex(indexTemlead);
        
        // fill data tfor agen name
        lblAgentName.setText(agent.getAgentName());
        
        //new TableFilterHeader(tblScorecardX, AutoChoices.ENABLED);
        chooserTransDate.setDate(null);
        chooserEvaluationDate.setDate(new Date());
       
        if (type.getIdScorecardType().compareTo(Constants.SCORECARD_TYPE_DIGITAL_ID) == 0) {
            lblPhone.setText("Email Address");
            lblDuration.setVisible(false);
            txtDuration.setVisible(false);
            jLabel6.setVisible(false);
            txtRecordingId.setVisible(false);
        } else if (type.getIdScorecardType().compareTo(Constants.SCORECARD_TYPE_OUTBOUND_ID) == 0) {
            lblSubject.setText("Purpose");
        }
        final WaitingDialog loadingDialog = new WaitingDialog(main, true);
        SwingWorker<?, ?> worker = new SwingWorker<Void, Void>() {
                @Override
                protected Void doInBackground() throws Exception {
                    loadData(scorecard);
                    return null;
                }

                @Override
                protected void done() {
                    loadingDialog.dispose();
                }
            };
            worker.execute();
            loadingDialog.setVisible(true);               
        
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        chooserTransDate = new com.toedter.calendar.JDateChooser();
        jLabel2 = new javax.swing.JLabel();
        txtOrderNo = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        lblSubject = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        cboTeamLeader = new javax.swing.JComboBox();
        txtPhone = new javax.swing.JTextField();
        lblPhone = new javax.swing.JLabel();
        lblFinalScore = new javax.swing.JLabel();
        jLabel10 = new javax.swing.JLabel();
        lblAgentName = new javax.swing.JLabel();
        btnSave = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();
        chooserEvaluationDate = new com.toedter.calendar.JDateChooser();
        lblWeek = new javax.swing.JLabel();
        txtSubject = new javax.swing.JTextField();
        btnChooseSubject = new javax.swing.JButton();
        lblDuration = new javax.swing.JLabel();
        txtDuration = new javax.swing.JFormattedTextField();
        listAttrPanel = new javax.swing.JPanel();
        lblEvaluatorName = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        txtZendeskTicketNumber = new javax.swing.JTextField();
        txtRecordingId = new javax.swing.JTextField();

        setClosable(true);
        setTitle("Agent Scorecard");
        setPreferredSize(new java.awt.Dimension(1000, 630));

        jPanel1.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 0, 0), 1, true));

        jLabel1.setText("Transaction Date");

        jLabel2.setText("Order #");

        txtOrderNo.setMaximumSize(new java.awt.Dimension(250, 2147483647));

        jLabel4.setText("Agent Name");

        lblSubject.setText("Subject");

        jLabel7.setText("Team Leader");

        txtPhone.setMaximumSize(new java.awt.Dimension(250, 2147483647));

        lblPhone.setText("Phone #");

        lblFinalScore.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        lblFinalScore.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        lblFinalScore.setText("Final Score : 0");

        jLabel10.setText("Evaluator ");

        lblAgentName.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        lblAgentName.setText("lbl_Agent_Name");

        btnSave.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/icon/save.png"))); // NOI18N
        btnSave.setText("Save");
        btnSave.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSaveActionPerformed(evt);
            }
        });

        jLabel3.setText("Evaluation Date");

        lblWeek.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        lblWeek.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        lblWeek.setText("Week");

        txtSubject.setMinimumSize(new java.awt.Dimension(574, 20));

        btnChooseSubject.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/icon/checklist.png"))); // NOI18N
        btnChooseSubject.setPreferredSize(new java.awt.Dimension(36, 25));
        btnChooseSubject.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnChooseSubjectActionPerformed(evt);
            }
        });

        lblDuration.setText("Duration (secs)");

        txtDuration.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter(new java.text.DecimalFormat("#0"))));

        listAttrPanel.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 0, 0), 1, true));
        listAttrPanel.setLayout(new javax.swing.BoxLayout(listAttrPanel, javax.swing.BoxLayout.Y_AXIS));

        lblEvaluatorName.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        lblEvaluatorName.setText("jLabel5");

        jLabel5.setText("Zendesk Ticket Number");

        jLabel6.setText("Recording Id");

        txtZendeskTicketNumber.setMinimumSize(new java.awt.Dimension(230, 20));

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(listAttrPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel1)
                                    .addComponent(jLabel3)
                                    .addComponent(jLabel4)
                                    .addComponent(jLabel7))
                                .addGap(48, 48, 48))
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                                .addComponent(jLabel5)
                                .addGap(19, 19, 19))
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                                .addComponent(lblSubject)
                                .addGap(94, 94, 94)))
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(lblAgentName)
                                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                        .addComponent(cboTeamLeader, javax.swing.GroupLayout.Alignment.TRAILING, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                        .addComponent(chooserTransDate, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 230, Short.MAX_VALUE)
                                        .addComponent(chooserEvaluationDate, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                        .addComponent(txtZendeskTicketNumber, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                                .addGap(35, 35, 35)
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addGroup(jPanel1Layout.createSequentialGroup()
                                        .addComponent(jLabel6)
                                        .addGap(18, 18, 18)
                                        .addComponent(txtRecordingId))
                                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                        .addComponent(lblWeek, javax.swing.GroupLayout.PREFERRED_SIZE, 329, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addGroup(jPanel1Layout.createSequentialGroup()
                                            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                                .addComponent(jLabel2)
                                                .addComponent(jLabel10)
                                                .addComponent(lblPhone))
                                            .addGap(30, 30, 30)
                                            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                                .addComponent(txtOrderNo, javax.swing.GroupLayout.DEFAULT_SIZE, 250, Short.MAX_VALUE)
                                                .addComponent(lblEvaluatorName)
                                                .addComponent(txtPhone, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))))
                            .addComponent(txtSubject, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGap(65, 65, 65)
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(jPanel1Layout.createSequentialGroup()
                                        .addComponent(lblDuration)
                                        .addGap(32, 32, 32)
                                        .addComponent(txtDuration, javax.swing.GroupLayout.DEFAULT_SIZE, 68, Short.MAX_VALUE))
                                    .addComponent(lblFinalScore, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(btnChooseSubject, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(btnSave)))))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel4)
                        .addComponent(lblAgentName))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(lblWeek, javax.swing.GroupLayout.Alignment.TRAILING)
                        .addComponent(lblFinalScore)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                    .addComponent(txtOrderNo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(jLabel2))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                    .addComponent(txtPhone, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(lblDuration)
                                    .addComponent(txtDuration, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                            .addComponent(lblPhone))
                        .addGap(9, 9, 9)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel10)
                            .addComponent(lblEvaluatorName))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(chooserEvaluationDate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel3))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(chooserTransDate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel1))
                        .addGap(6, 6, 6)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(cboTeamLeader, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel7))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)))
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btnSave)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel5)
                            .addComponent(jLabel6)
                            .addComponent(txtZendeskTicketNumber, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(txtRecordingId, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(lblSubject)
                                .addComponent(txtSubject, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(btnChooseSubject, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(listAttrPanel, javax.swing.GroupLayout.PREFERRED_SIZE, 537, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnChooseSubjectActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnChooseSubjectActionPerformed
        SubjectChooser subjectChooser = new SubjectChooser(this, selectedSubject);
        subjectChooser.setModal(true);
        main.addNewInternalFrame(subjectChooser);
    }//GEN-LAST:event_btnChooseSubjectActionPerformed

    private void btnSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSaveActionPerformed
        if (validationForm()) {
            final WaitingDialog loadingDialog = new WaitingDialog(main, true);
            final AgentScorecard agentScorecard = this;
            SwingWorker<Integer, Void> worker = new SwingWorker<Integer, Void>() {
                @Override
                protected Integer doInBackground() throws Exception {
                    Integer scorecardId = new ScorecardLogic().saveOrUpdateScorecard(preareData());

                    return scorecardId;
                }

                @Override
                protected void done() {
                    loadingDialog.dispose();
                }
            };
            worker.execute();
            loadingDialog.setVisible(true);

            Integer scorecardId = 0;
            try {
                scorecardId = worker.get().intValue();
            } catch (InterruptedException ex) {
                Logger.getLogger(AgentScorecard.class.getName()).log(Level.SEVERE, null, ex);
            } catch (ExecutionException ex) {
                Logger.getLogger(AgentScorecard.class.getName()).log(Level.SEVERE, null, ex);
            }
            if (scorecardId > 0) {
                final Scorecard sc = new ScorecardLogic().findScorecardByIdIncludeAgentSubject(scorecardId);
                currentScorecard = sc;
                isUpdate = true;
                final WaitingDialog loadingDialog2 = new WaitingDialog(main, true);
                SwingWorker<Void, Void> workerLoadData = new SwingWorker<Void, Void>() {
                    @Override
                    protected Void doInBackground() throws Exception {
                        loadData(sc);                       
                        return null;
                    }
                    @Override
                    protected void done() {
                    loadingDialog2.dispose();
                    agentScorecard.updateUI();
                }
                };
                workerLoadData.execute();  
                loadingDialog2.setVisible(true);
                JOptionPane.showMessageDialog(main, "Save scorecard successful !");
            } else {
                JOptionPane.showMessageDialog(main, "Save scorecard failed !");
            }

        }
    }//GEN-LAST:event_btnSaveActionPerformed


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnChooseSubject;
    private javax.swing.JButton btnSave;
    private javax.swing.JComboBox cboTeamLeader;
    private com.toedter.calendar.JDateChooser chooserEvaluationDate;
    private com.toedter.calendar.JDateChooser chooserTransDate;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JLabel lblAgentName;
    private javax.swing.JLabel lblDuration;
    private javax.swing.JLabel lblEvaluatorName;
    private javax.swing.JLabel lblFinalScore;
    private javax.swing.JLabel lblPhone;
    private javax.swing.JLabel lblSubject;
    private javax.swing.JLabel lblWeek;
    private javax.swing.JPanel listAttrPanel;
    private javax.swing.JFormattedTextField txtDuration;
    private javax.swing.JTextField txtOrderNo;
    private javax.swing.JTextField txtPhone;
    private javax.swing.JTextField txtRecordingId;
    public javax.swing.JTextField txtSubject;
    private javax.swing.JTextField txtZendeskTicketNumber;
    // End of variables declaration//GEN-END:variables
    private void loadData(Scorecard scorecard) {
        listAttrPanel.removeAll();
        List<ScorecardDetailsResult> listScorecardDetailsResult = new ArrayList<>();
        List<ScorecardGroupAttributeResult> listScorecardGroupAttributeResult = new ArrayList<>();
        lblEvaluatorName.setText(main.getAgentLogin().getAgentName());
        if (isUpdate) {
            chooserTransDate.setDate(scorecard.getTransactionDate());
            chooserEvaluationDate.setDate(scorecard.getEvalutationDate());
            txtOrderNo.setText(scorecard.getOrderNo());
            cboTeamLeader.setSelectedIndex(getIndexAgent(mapAgent.get(scorecard.getFkAgentTeamlead()).getIdAgent(), cboTeamLeader));
            //cboEvaluator.setSelectedIndex(getIndexAgent(mapAgent.get(scorecard.getFkAgentEvaluator()).getIdAgent(), cboEvaluator));
            txtPhone.setText(scorecard.getPhoneNo());
            txtDuration.setValue(scorecard.getDuration());
//            cboSubject.setSelectedIndex(getIndexSubject(scorecard.getSubject().getSubject()));
            txtSubject.setText(scorecard.getSubjectName());
            this.setSelectedSubject(scorecard.getSubject());
            lblWeek.setText(Constants.LABEL_WEEK_SCORECARD + DateUtils.getWeekByDate(scorecard.getEvalutationDate()));
            listScorecardDetails = new ScorecardDetailsLogic().findScorecardDetailsByScorecardId(scorecard.getIdScorecard());
            listScorecardDetailsResult = new ScorecardDetailsResultLogic().findScorecardDetailsResultByScorecardId(scorecard.getIdScorecard());            
            listScorecardGroupAttributeResult = new ScorecardGroupAttributeResultLogic().findByScorecardId(scorecard.getIdScorecard());
            lblFinalScore.setText("Final Score : "+scorecard.getTotalScore());                
            txtZendeskTicketNumber.setText(scorecard.getZendeskTicketNumber());
            txtRecordingId.setText(scorecard.getRecordingId());
        } else {
            lblWeek.setText(Constants.LABEL_WEEK_SCORECARD + DateUtils.getCurrentWeekOfYear());
        }
        
        listScheme = new SchemeLogic().findAllScheme();
        listScObjectTable.clear();
        groups = new AttributeGroupLogic().findAttrGroupByType(type.getIdScorecardType());
        
        Map<Integer,Scheme> mapScheme = new TreeMap<>();
        for (int i = 0;i<listScorecardDetails.size();i++) {
            ScorecardDetails scorecardDetails = listScorecardDetails.get(i);
            mapScheme.put(scorecardDetails.getAttribute().getIdAttribute(), scorecardDetails.getScheme());
        }
        
        Map<Integer,Double> mapCalculatedScore = new TreeMap<>();
        for (int i = 0;i<listScorecardDetailsResult.size();i++) {
            ScorecardDetailsResult scdetailsResult = listScorecardDetailsResult.get(i);
            mapCalculatedScore.put(scdetailsResult.getAttribute().getIdAttribute(), scdetailsResult.getResult());
        }
        Map<Integer,String> mapComment = new TreeMap<>();        
        for (int i = 0;i<listScorecardGroupAttributeResult.size();i++) {
            ScorecardGroupAttributeResult result = listScorecardGroupAttributeResult.get(i);
            mapComment.put(result.getAttributeGroup().getIdAttributeGroup(),result.getComment());
        }
        for (AttributeGroup group : groups) {
            JTableX table = createNewTable(group, mapScheme, mapCalculatedScore);
            JLabel groupName = new JLabel("          "+group.getAttributeGroupName() + " ("+group.getAttributeGroupWeight()+"%)");
            Font font = groupName.getFont();
            // same font but bold
            Font boldFont = new Font(font.getFontName(), Font.BOLD, font.getSize());
            groupName.setFont(boldFont);
            groupName.setHorizontalAlignment(SwingConstants.LEFT);
            
            // apply tabindex only editable cell
            new EditableCellFocusAction(table, KeyStroke.getKeyStroke("TAB"));
            // hide first column
            table.getColumnModel().getColumn(0).setMinWidth(0);
            table.getColumnModel().getColumn(0).setMaxWidth(0);
            table.getColumnModel().getColumn(0).setWidth(0);
            
            // setting width for column attribute
            table.getColumnModel().getColumn(Constants.TABLE_SCORECARD_DETAILS_COLUMN_ATTRIBUTE).setMinWidth(300);
            table.getColumnModel().getColumn(Constants.TABLE_SCORECARD_DETAILS_COLUMN_ATTRIBUTE).setMaxWidth(300);
            table.getColumnModel().getColumn(Constants.TABLE_SCORECARD_DETAILS_COLUMN_ATTRIBUTE).setWidth(300);
            
            table.getColumnModel().getColumn(Constants.TABLE_SCORECARD_DETAILS_COLUMN_EVALUATE_SCORE).setMinWidth(200);
            table.getColumnModel().getColumn(Constants.TABLE_SCORECARD_DETAILS_COLUMN_EVALUATE_SCORE).setMaxWidth(200);
            table.getColumnModel().getColumn(Constants.TABLE_SCORECARD_DETAILS_COLUMN_EVALUATE_SCORE).setWidth(200);
            
            
            //table.setBorder(BorderFactory.createLineBorder(Color.yellow));
            // create panel to glue label align left
            JPanel panel = new JPanel();
            panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));
            panel.add(groupName);            
            panel.add(Box.createHorizontalGlue());
            listAttrPanel.add(panel);
            
            // panel content table
            JPanel panelTableAndComment = new JPanel();
            //panelTableAndComment.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS));
            //panelTableAndComment.setAlignmentY(Component.TOP_ALIGNMENT);
            panelTableAndComment.add(table);
            
            
            
            JTextArea txtComment = new JTextArea(mapComment.get(group.getIdAttributeGroup()));            
            txtComment.setLineWrap(true);
                        
            JScrollPane scrollPane = new JScrollPane(txtComment);
            scrollPane.setPreferredSize(new Dimension(230, table.getModel().getRowCount() * 22));
            scrollPane.setMaximumSize(new Dimension(230, table.getModel().getRowCount() * 22));
            scrollPane.setMinimumSize(new Dimension(230, table.getModel().getRowCount() * 22));
            panelTableAndComment.add(scrollPane);
            
            
            if (table.getModel().getRowCount() > 1) {
                panelTableAndComment.setPreferredSize(new Dimension(830, table.getModel().getRowCount() * 25));
                panelTableAndComment.setMaximumSize(new Dimension(830, table.getModel().getRowCount() * 25));
                panelTableAndComment.setMinimumSize(new Dimension(830, table.getModel().getRowCount() * 25));
                
            } else {
                panelTableAndComment.setPreferredSize(new Dimension(830, 40));
                panelTableAndComment.setMaximumSize(new Dimension(830, 40));
                panelTableAndComment.setMinimumSize(new Dimension(830, 40));
            }
                                              
            listAttrPanel.add(panelTableAndComment);           
        }
        
        listAttrPanel.add(Box.createVerticalGlue());
        
        
    }
    
    private JTableX createNewTable(AttributeGroup group,Map<Integer,Scheme> mapScheme,Map<Integer,Double> mapCalculatedScore) {
        Set<Attribute> listAttr = group.getAttributes();
        List<ScorecardDetailObjTable> listScObjectTable = new ArrayList<ScorecardDetailObjTable>();
        for (Attribute attr : listAttr) {
            ScorecardDetailObjTable detail = new ScorecardDetailObjTable();
                detail.setAttributeGroup(group);
                detail.setAttribute(attr);                
                
                if (isUpdate) {
                    detail.setScore(mapScheme.get(attr.getIdAttribute()));
                    detail.setCalculatedScore(mapCalculatedScore.get(attr.getIdAttribute()));
                }
                listScObjectTable.add(detail);
        }
        JTableX table = new JTableX(new ScorecardDetailsTableModel(listScObjectTable));
        table.setRowSelectionAllowed(false);
        table.setColumnSelectionAllowed(false);
        table.setRowHeight(Constants.HEIGHT_OF_ROW_TABLE_SCORECARD_ASSESSMENT);
        //        DefaultTableCellRenderer renderer = (DefaultTableCellRenderer) tblScorecardX.getTableHeader().getDefaultRenderer();
//        renderer.setHorizontalAlignment(0);
        DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer();
        centerRenderer.setHorizontalAlignment(SwingConstants.CENTER);
        table.getColumnModel().getColumn(Constants.TABLE_SCORECARD_DETAILS_COLUMN_CALCULATED_SCORE).setCellRenderer( centerRenderer );
        
        // set color for column evaluation score        
        ColorColumnRenderer columnRenderer = new ColorColumnRenderer(Color.decode("#39698A"), Color.WHITE);
        columnRenderer.setHorizontalAlignment( SwingConstants.CENTER );
        table.getColumnModel().getColumn(Constants.TABLE_SCORECARD_DETAILS_COLUMN_EVALUATE_SCORE).setCellRenderer(columnRenderer);
        
        RowEditorModel rm = new RowEditorModel();
        table.setRowEditorModel(rm);
        int k = 0;
        
            for (Attribute attr : listAttr) {
                JComboBox cb = new JComboBox();
                for (Scheme sh : listScheme) {
                    if (attr.getSchemeType().compareTo(sh.getType()) == 0) {
                        cb.addItem(new SchemeComboItem(sh));
                    }
                }

                cb.addKeyListener(new KeyAdapter() {

                    @Override
                    public void keyReleased(KeyEvent ke) {
                        super.keyReleased(ke);
                        int i;
                        String keypressed = Character.toString(ke.getKeyChar());
                        if (tryParseInt(keypressed)) {
                            i = Integer.parseInt(keypressed);
                            JComboBox currentcb = ((JComboBox) ((Component) ke
                                    .getComponent()));
                            if (i <= currentcb.getItemCount()) {                                
                                currentcb.showPopup();
                                currentcb.setSelectedIndex(i - 1);
                                currentcb.updateUI();
                            }
                        }
                    }

                    boolean tryParseInt(String value) {
                        try {
                            Integer.parseInt(value);
                            return true;
                        } catch (NumberFormatException nfe) {
                            return false;
                        }
                    }
                });

                DefaultCellEditor ed = new DefaultCellEditor(cb);
                rm.addEditorForRow(k, ed);
                k++;
            }
        
        
        return table;
    }
    
    private Scorecard preareData() {
        Scorecard scorecard;
        if (!isUpdate) {
            scorecard = new Scorecard();
//            scorecard.setFkAccountCreatedBy(agentLogin.getAccounts().);
//            scorecard.setFkAccountUpdatedBy(agentLogin.getIdAgent());
            scorecard.setCreatedAt(new Date());
            scorecard.setUpdatedAt(new Date());
            scorecard.setYear(DateUtils.getCurrentYear());
            scorecard.setMonth(DateUtils.getCurrentMonth());
            scorecard.setWeek(DateUtils.getCurrentWeekOfYear());
            scorecard.setQuarter(DateUtils.getQuarterByMonth(scorecard.getMonth()));
        } else {
            scorecard = currentScorecard;
            scorecard.setUpdatedAt(new Date());
//            scorecard.setFkAccountUpdatedBy(agentLogin.getIdAgent());
        }
        scorecard.setEvalutationDate(chooserEvaluationDate.getDate());
        scorecard.setTransactionDate(chooserTransDate.getDate());
        scorecard.setOrderNo(txtOrderNo.getText());
        scorecard.setAgent(agent);
        scorecard.setScorecardType(type);
        AgentComboItem itemTeamLead = (AgentComboItem) cboTeamLeader.getSelectedItem();
        if (itemTeamLead != null) {
            scorecard.setFkAgentTeamlead(itemTeamLead.getValue().getIdAgent());
        }
        //AgentComboItem itemEvaluator = (AgentComboItem) cboEvaluator.getSelectedItem();
        //scorecard.setFkAgentEvaluator(itemEvaluator.getValue().getIdAgent());
        scorecard.setFkAgentEvaluator(main.getAgentLogin().getIdAgent());
        scorecard.setPhoneNo(txtPhone.getText().trim());
        scorecard.setEmail(txtPhone.getText().trim());
        if (type.getIdScorecardType().compareTo(Constants.SCORECARD_TYPE_DIGITAL_ID) != 0) {
            scorecard.setDuration(Integer.parseInt(txtDuration.getValue().toString()));
        }
        scorecard.setScorecardType(type);
        scorecard.setSubject(selectedSubject);
        scorecard.setSubjectName(txtSubject.getText().trim());
        scorecard.setZendeskTicketNumber(txtZendeskTicketNumber.getText().trim());
        scorecard.setRecordingId(txtRecordingId.getText().trim());

        Set<ScorecardDetails> setScDetails = new HashSet<>();
        Set<ScorecardDetailsResult> setScDetailResult = new HashSet<>();
        Set<ScorecardGroupAttributeResult> setScGroupAttriResult = new HashSet<>();
        double totalScore = 0;
        boolean zero = checkZero();
        Map<Integer,String> mapComment = new TreeMap<>();
        for (Component component : listAttrPanel.getComponents()) {
            if (component instanceof JPanel) {
                JPanel panelChild = (JPanel)component;
                Integer idAttrGroup = 0;
                for (Component childCom : panelChild.getComponents()) {                    
                    
                    if (childCom instanceof JTableX) {
                        JTableX table = (JTableX) childCom;
                        ScorecardDetailsTableModel model = (ScorecardDetailsTableModel) table.getModel();
                        double groupScore = 0;
                        ScorecardGroupAttributeResult scGroupDetailsResult = new ScorecardGroupAttributeResult();
                        for (int i = 0; i < model.getRowCount(); i++) {
                            // initial object
                            ScorecardDetails scDetails = new ScorecardDetails();
                            ScorecardDetailsResult scDetailsResult = new ScorecardDetailsResult();

                            Double score = 0.0;

                            // get value from table
                            AttributeGroup attributeGroup = (AttributeGroup) model.getValueAt(i, Constants.TABLE_SCORECARD_DETAILS_COLUMN_ATTRIBUTE_GROUP);
                            Attribute attribute = (Attribute) model.getValueAt(i, Constants.TABLE_SCORECARD_DETAILS_COLUMN_ATTRIBUTE);
                            idAttrGroup = attributeGroup.getIdAttributeGroup();
                            Scheme scheme = (Scheme) model.getValueAt(i, Constants.TABLE_SCORECARD_DETAILS_COLUMN_EVALUATE_SCORE);
                            if (scheme == null) {
                                for (Scheme sch : listScheme) {
                                    if (sch.getType().compareTo(attribute.getSchemeType()) == 0) {
                                        if (sch.getValue() == null) {
                                            scheme = sch;
                                        }
                                    }
                                }
                            }
                            if (scheme.getValue() != null) {
                                Object objScore = ApplicationCommon.calculateResultOfAttribute(attribute, scheme, getValueAttrNA(attributeGroup, model), attributeGroup.getAttributeGroupWeight());

                                if (objScore != null) {
                                    score = Double.parseDouble(objScore.toString());
                                    groupScore += score;
                                    totalScore += score;
                                }
                            } else {
                                score = null;
                            }
                            if (zero) {
                                score = 0.0;
                                groupScore += score;
                                totalScore += score;
                            }
                            // fill data for ScorecardDetails
                            scDetails.setAttribute(attribute);
                            scDetails.setScheme(scheme);
                            scDetails.setScorecard(scorecard);
                            // fill data for ScorecardDetailsResult
                            scDetailsResult.setAttribute(attribute);
                            scDetailsResult.setResult(score);
                            scDetailsResult.setScorecard(scorecard);
                            // fill data for ScorecardGroupAttributeResult
                            scGroupDetailsResult.setAttributeGroup(attributeGroup);
                            scGroupDetailsResult.setScorecard(scorecard);
                            
                            // add to set
                            setScDetails.add(scDetails);
                            setScDetailResult.add(scDetailsResult);

                        }
                        //scGroupDetailsResult.setComment(comment);
                        scGroupDetailsResult.setScore(groupScore);

                        setScGroupAttriResult.add(scGroupDetailsResult);
                        
                    }
                    if (childCom instanceof JScrollPane) {
                        JScrollPane scrollPane = (JScrollPane)childCom;
                        JTextArea txtComment = (JTextArea)scrollPane.getViewport().getView();    
                        String comment = txtComment.getText();
                        mapComment.put(idAttrGroup,comment);
                    }
                }
            }
        }
        // min of total score is 0
        if (totalScore < 0) {
            totalScore = 0L;
        }
        
        for (Integer key : mapComment.keySet()) {
            for (ScorecardGroupAttributeResult rs : setScGroupAttriResult) {
                if (rs.getAttributeGroup().getIdAttributeGroup().compareTo(key) == 0) {
                    rs.setComment(mapComment.get(key));
                }
            }
        }
        scorecard.setTotalScore(totalScore);
        scorecard.setScorecardDetailses(setScDetails);
        scorecard.setScorecardDetailsResults(setScDetailResult);
        scorecard.setScorecardGroupAttributeResult(setScGroupAttriResult);

        return scorecard;
    }
    
    private int getIndexAgent(Integer id, JComboBox combo) {
        int index = 0;
        
        for (int i = 0; i< combo.getItemCount(); i++) {
            AgentComboItem item = (AgentComboItem)combo.getItemAt(i);
            if (item.getValue().getIdAgent().compareTo(id) == 0) {
                index = i;
                break;
            }
        }
        return index;
    }    
    
    private boolean validationForm() {
        if (chooserTransDate.getDate() == null) {
            JOptionPane.showMessageDialog(main, "Please choose : Transaction Date");
            chooserTransDate.requestFocus();
            return false;
        }
        if (txtOrderNo.getText().trim().equals("")) {
            JOptionPane.showMessageDialog(main, "Please input : Order #");
            txtOrderNo.requestFocus();
            return false;
        }
        if (txtSubject.getText().trim().equals("")) {
            if (type.getIdScorecardType().compareTo(Constants.SCORECARD_TYPE_OUTBOUND_ID) == 0) {
                JOptionPane.showMessageDialog(main, "Please input : Purpose");
            } else {
                JOptionPane.showMessageDialog(main, "Please input : Subject");
            }
            btnChooseSubject.requestFocus();
            return false;
        }

        if (txtPhone.getText().trim().equals("")) {
            if (type.getIdScorecardType().compareTo(Constants.SCORECARD_TYPE_DIGITAL_ID) == 0) {
                JOptionPane.showMessageDialog(main, "Please input : Email Address");
            } else {
                JOptionPane.showMessageDialog(main, "Please input : Phone");
            }
            txtPhone.requestFocus();
            return false;
        }
        if (txtZendeskTicketNumber.getText().trim().equals("")) {
            JOptionPane.showMessageDialog(main, "Please input : Zendesk Ticket Number");
            txtZendeskTicketNumber.requestFocus();
            return false;
        }
        if (type.getIdScorecardType().compareTo(Constants.SCORECARD_TYPE_DIGITAL_ID) != 0) {
            if (txtDuration.getValue() == null) {
                JOptionPane.showMessageDialog(main, "Please input : Duration");
                txtDuration.requestFocus();
                return false;
            }
            if (txtRecordingId.getText().trim().equals("")) {
                JOptionPane.showMessageDialog(main, "Please input : Recording Id");
                txtRecordingId.requestFocus();
                return false;
            }
        }
        
        for (Component com : listAttrPanel.getComponents()) {
            if (com instanceof JPanel) {
                JPanel panelChild = (JPanel) com;
                for (Component compo : panelChild.getComponents()) {
                    if (compo instanceof JTableX) {
                        JTableX table = (JTableX) compo;
                        ScorecardDetailsTableModel model = (ScorecardDetailsTableModel) table.getModel();
                        for (int i = 0; i < model.getRowCount(); i++) {
                            Scheme scheme = (Scheme) model.getValueAt(i, Constants.TABLE_SCORECARD_DETAILS_COLUMN_EVALUATE_SCORE);
                            if (scheme == null) {
                                JOptionPane.showMessageDialog(main, "Please input all attribute");
                                return false;
                            }
                        }
                    }
                }

            }
        }
        return true;
    }
    
    private boolean checkZero() {
        for (Component component : listAttrPanel.getComponents()) {
            if (component instanceof JPanel) {
                JPanel panelChild = (JPanel) component;
                for (Component com : panelChild.getComponents()) {
                    if (com instanceof JTableX) {
                        JTableX table = (JTableX) com;
                        ScorecardDetailsTableModel model = (ScorecardDetailsTableModel) table.getModel();
                        for (int i = 0; i < model.getRowCount(); i++) {
                            Object objScore = model.getValueAt(i, Constants.TABLE_SCORECARD_DETAILS_COLUMN_CALCULATED_SCORE);
                            if (objScore != null) {
                                double score = Double.parseDouble(objScore.toString());
                                if (score == -100) {
                                    return true;
                                }
                            }
                        }
                    }
                }

            }
        }

        return false;
    }
    
    @Override
    public void doDefaultCloseAction() {       
        int opt = JOptionPane.showConfirmDialog(null,
                "Are you sure to close this window?", "Confirm",
                JOptionPane.YES_NO_OPTION,
                JOptionPane.QUESTION_MESSAGE);
        if (opt == JOptionPane.YES_OPTION) {
            super.doDefaultCloseAction();
            final WaitingDialog loadingDialog = new WaitingDialog(main, true);
            //final AgentScorecard agentScorecard = this;
            SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {
                @Override
                protected Void doInBackground() throws Exception {
                    qaWorkList.refreshData();

                    return null;
                }

                @Override
                protected void done() {
                    loadingDialog.dispose();
                }
            };
            worker.execute();
            loadingDialog.setVisible(true);
            
        } else {
            return;
        }              
    }
    
    /**
     * get value of scheme NA for calculate score
     * @param attributeGroup
     * @param model
     * @return 
     */
    private long getValueAttrNA(AttributeGroup attributeGroup, ScorecardDetailsTableModel model) {
        long value = 0;
        for (int i = 0; i < model.getRowCount();i++) {
            AttributeGroup attrGroup = (AttributeGroup) model.getValueAt(i, Constants.TABLE_SCORECARD_DETAILS_COLUMN_ATTRIBUTE_GROUP);
            if (attrGroup.getIdAttributeGroup().compareTo(attributeGroup.getIdAttributeGroup()) == 0) {
                Scheme scheme = (Scheme) model.getValueAt(i, Constants.TABLE_SCORECARD_DETAILS_COLUMN_EVALUATE_SCORE);
                    if (scheme == null || scheme.getValue() == null) {
                        Attribute attribute = (Attribute) model.getValueAt(i, Constants.TABLE_SCORECARD_DETAILS_COLUMN_ATTRIBUTE);
                        value += attribute.getAttributeWeight();
                    }
            } 
        }
        return value;
    }
    
    public Subject getSelectedSubject() {
        return selectedSubject;
    }

    public void setSelectedSubject(Subject selectedSubject) {
        this.selectedSubject = selectedSubject;
    }
    
    
}
